var _historys = [];
var _links = [
    {name:"Wiki", url:"http://wiki/display/GIP/"},
    {name:"乐元素工作助手", url:"https://chrome.google.com/webstore/detail/he-working-care/djjfgioemfldhpiihidfheoicnlkldof", css:{color:"red"}}
];

init();
//
function init(){
    $("#swap_list h4 span").click(function(e){
        var url  = chrome.extension.getURL('options.html');
        chrome.tabs.create({url:url});
    });
    //
    if(localStorage['history'] && (localStorage['history'] !== "{}")){
        var data = {};
        try{
            data = JSON.parse(localStorage['history']);
        }catch(e){
            //
        }
        for(var s in data){
            var item = {};
            item = data[s];
            item.name = s;
            _historys.push(item);
        }
    }
    // console.log(_historys);
    createProfiles(_historys);
    createTools(_links);
    //中间灰线  height:120px;
    if($("#swap_list").height() < 120){
        $("#swap_list").height(120);
    }
}

function createProfiles(list){
    $("#swap_list a").remove();
    for(var i = 0; i < list.length; i++){
        var a = document.createElement("a");
        $(a).text(list[i].name);
        $(a).attr("href", "#");
        $(a).attr("name", list[i].name);
        $("#swap_list").append(a);
        $(a).click(function(e){
            var bmp = chrome.extension.getBackgroundPage();
            // console.log($(e.currentTarget).attr("name"));
            bmp.insertScript($(e.currentTarget).attr("name"));
            window.close();
            // chrome.tabs.create({url:"http://www.ibio8.com"});
        });
    }
    //
    if(list.length <= 0){
        var a = document.createElement("a");
        $(a).text("add a profile now!");
        $(a).attr("href", "#");
        $("#swap_list").append(a);
        $(a).click(function(e){
            var url  = chrome.extension.getURL('options.html');
            chrome.tabs.create({url:url});
        });
    }
}

function createTools(list){
    $("#recommend_list a").remove();
    for(var i = 0; i < list.length; i++){
        var a = document.createElement("a");
        $(a).text(list[i].name);
        $(a).attr("href", "#");
        $(a).attr("index", i);
        if(list[i].css){
            $(a).css(list[i].css);
        }
        $("#recommend_list").append(a);
        $(a).click(function(e){
            var index = parseInt($(e.currentTarget).attr("index"));
            chrome.tabs.create({url:list[index].url});
        });
    }
}
